<script setup lang="ts">
import { useDark, useThrottleFn, useWindowSize } from '@vueuse/core'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { onMounted, watch } from 'vue'
import { ScreenEnum } from './enums/appEnums'
import useAppStore from './stores/modules/app'
import useSettingStore from './stores/modules/setting'
import useUserStore from './stores/modules/user'
const appStore = useAppStore()
const settingStore = useSettingStore()
const elConfig = {
    zIndex: 3000,
    locale: zhCn
} 
const isDark = useDark()
const userStore = useUserStore()
onMounted(async () => {
    //设置主题色
    settingStore.setTheme(isDark.value)
    if (userStore.token) {
        // 获取用户信息
        const hasGetUserInfo = Object.keys(userStore.userInfo).length !== 0
        if (!hasGetUserInfo) {
            await userStore.getUserInfoFun()
        }
    }
})

const { width } = useWindowSize()
watch(
    width,
    useThrottleFn((value) => {
        if (value > ScreenEnum.SM) {
            appStore.setMobile(false)
            appStore.toggleCollapsed(false)
        } else {
            appStore.setMobile(true)
            appStore.toggleCollapsed(true)
        }
        if (value < ScreenEnum.MD) {
            appStore.toggleCollapsed(true)
        }
    }),
    {
        immediate: true
    }
)

// const autoRedirect = ref(true);
// const baseUrl = window.location.origin;
// const webUrl = `${baseUrl}/web`;
// const mobileUrl = `${baseUrl}/H5`;

// // 设备检测函数
// const detectDevice = () => {
//   const userAgent = navigator.userAgent.toLowerCase();
//   return /mobile|android|iphone|ipad|ipod/i.test(userAgent);
// };

// onMounted(() => {
//   try {
//     const targetUrl = detectDevice() ? mobileUrl : webUrl;
//     window.location.href = targetUrl;
//   } catch (error) {
//     console.error('自动跳转失败:', error);
//     autoRedirect.value = false;
//   }
// });


const autoRedirect = ref(true);
const shouldRedirect = ref(true);
const baseUrl = 'https://www.cqjsyh.com';
const webUrl = `${baseUrl}/web`;
const mobileUrl = `${baseUrl}/H5`;
const isMobile = ref(false);
const breakpoint = 768; // 桌面/移动断点

// 设备检测函数
const detectDevice = () => {
  const userAgent = navigator.userAgent.toLowerCase();
  const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
  const isMobileByAgent = /mobile|android|iphone|ipad|ipod/i.test(userAgent);
  const isMobileByWidth = window.innerWidth < breakpoint;
  
  return isMobileByAgent || (isTouchDevice && isMobileByWidth);
};



// 判断是否需要跳转
const checkIfNeedRedirect = () => {
  const currentPath = window.location.href // 获取当前路径
  
  const isOnWebPath = currentPath.includes('/web');
  const isOnMobilePath = currentPath.includes('/h5');
  console.log('isMobile======================================',isMobile.value)

  console.log('currentPath======================================',currentPath)
  console.log('isOnWebPath======================================',isOnWebPath)
  console.log('isOnMobilePath======================================',isOnMobilePath)
  // 如果已经在正确的路径上，则不需要跳转
  if ((isMobile.value && isOnMobilePath) || (!isMobile.value && isOnWebPath)) {
    return false;
  }
  
  // 其他情况需要跳转
  return true;
};

// 执行跳转
const redirect = () => {
  try {
    if (!shouldRedirect.value) {
      console.log('当前页面已匹配设备类型，跳过重定向');
      return;
    }
    
    const targetUrl = isMobile.value ? mobileUrl : webUrl;
    window.location.href = targetUrl;
  } catch (error) {
    console.error('自动跳转失败:', error);
    autoRedirect.value = false;
  }
};

// 窗口大小变化监听
const handleResize = () => {
  const prevIsMobile = isMobile.value;
  isMobile.value = detectDevice();
  
  // 只有在设备类型变化且需要跳转时才执行
  if (prevIsMobile !== isMobile.value) {
    shouldRedirect.value = checkIfNeedRedirect();
    if (shouldRedirect.value) {
      redirect();
    }
  }
};

onMounted(() => {
  isMobile.value = detectDevice();
  shouldRedirect.value = checkIfNeedRedirect();
  
  if (shouldRedirect.value) {
    redirect();
  }
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  // 移除监听，防止内存泄漏
  window.removeEventListener('resize', handleResize);
});
</script>

<template>
    <el-config-provider :locale="elConfig.locale" :z-index="elConfig.zIndex">
        <router-view />
    </el-config-provider>
</template>

<style>
    #app {
        width: 100%;
        min-height: 100vh;
        min-width: 1200px;
        background: #F8F8F8 url('../src/assets/images/bodybg.jpg') ;
    }
    .el-message{
      z-index: 99999 !important;
    }
</style>
